Telegram Group & Telegram Channel
Наверное, самая распространённая ошибка новичков в Python — это использование изменяемого объекта в качестве значения по умолчанию для аргумента функции. Такой объект будет общим для всех вызовов функции, что может привести к неожиданным результатам:


def append_length(lst=[]):
lst.append(len(lst))
return lst

print(append_length([1, 2])) # [1, 2, 2]
print(append_length()) # [0]
print(append_length()) # [0, 1]


Однако в некоторых случаях, например при реализации кешей, такое поведение может быть полезным:


def fact(x, cache={0: 1}):
if x not in cache:
cache[x] = x * fact(x - 1)
return cache[x]

print(fact(5))


В этом примере мы сохраняем вычисленные значения факториала внутри значения аргумента по умолчанию. Причём к этому значению даже можно обратиться напрямую:


>>> fact.__defaults__
({0: 1, 1: 1, 2: 2, 3: 6, 4: 24, 5: 120},)


👉@BookPython



tg-me.com/BookPython/3670
Create:
Last Update:

Наверное, самая распространённая ошибка новичков в Python — это использование изменяемого объекта в качестве значения по умолчанию для аргумента функции. Такой объект будет общим для всех вызовов функции, что может привести к неожиданным результатам:


def append_length(lst=[]):
lst.append(len(lst))
return lst

print(append_length([1, 2])) # [1, 2, 2]
print(append_length()) # [0]
print(append_length()) # [0, 1]


Однако в некоторых случаях, например при реализации кешей, такое поведение может быть полезным:


def fact(x, cache={0: 1}):
if x not in cache:
cache[x] = x * fact(x - 1)
return cache[x]

print(fact(5))


В этом примере мы сохраняем вычисленные значения факториала внутри значения аргумента по умолчанию. Причём к этому значению даже можно обратиться напрямую:


>>> fact.__defaults__
({0: 1, 1: 1, 2: 2, 3: 6, 4: 24, 5: 120},)


👉@BookPython

BY Библиотека Python разработчика | Книги по питону


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/BookPython/3670

View MORE
Open in Telegram


Библиотека Python разработчика Telegram | DID YOU KNOW?

Date: |

Telegram Gives Up On Crypto Blockchain Project

Durov said on his Telegram channel today that the two and a half year blockchain and crypto project has been put to sleep. Ironically, after leaving Russia because the government wanted his encryption keys to his social media firm, Durov’s cryptocurrency idea lost steam because of a U.S. court. “The technology we created allowed for an open, free, decentralized exchange of value and ideas. TON had the potential to revolutionize how people store and transfer funds and information,” he wrote on his channel. “Unfortunately, a U.S. court stopped TON from happening.”

A Telegram spokesman declined to comment on the bond issue or the amount of the debt the company has due. The spokesman said Telegram’s equipment and bandwidth costs are growing because it has consistently posted more than 40% year-to-year growth in users.

Библиотека Python разработчика from cn


Telegram Библиотека Python разработчика | Книги по питону
FROM USA